import {$http} from '@bana/miniapp-common-util'

Component({
  properties: {
    typeCode: {
      type: String,
      value: '',
      observer(newVal, oldVal) {
        console.log('cms-form typeCode observer=========', newVal, oldVal)
        this._findColumn()
      }
    },
    namespace: {
      type: String,
      value: '',
      observer(newVal, oldVal) {
        console.log('cms-form namespace observer=========', newVal, oldVal)
        this._findColumn()
      }
    },
    formClass: {
      type: String,
      value: ''
    },
    numberColumns: {
      type: Array,
      value: []
    },
    idcardColumns: {
      type: Array,
      value: []
    },
    phoneColumns: {
      type: Array,
      value: []
    },
    emailColumns: {
      type: Array,
      value: []
    },
    saveButtonName: {
      type: String,
      value: '提交'
    }
  },
  data: {
    typeCodeColumnList: [],
    requiredColumnList: [],
    addUpdParam: {}
  },
  created() {

  },
  observers: {
  },
  lifetimes: {
  },
  methods: {
    _findColumn() {
      const that = this
      wx.showLoading({
        title: '加载中',
      })
      $http.post({
        url: `cmsv2/content/columnManage/findByTypeCode2/${that.data.typeCode}${that.data.namespace
          ? '?namespace=' + that.data.namespace : ''}`,
        success(res) {
          console.log('_findColumn res', res)
          const list = that._handleContentColumnList(res.data.resultData)
          that.setData({
            typeCodeColumnList: list
          })
          console.log('_findColumn typeCodeColumnList', that.data.typeCodeColumnList)
          wx.hideLoading()
        }
      })
    },
    _handleContentColumnList(list = []) {
      let resList = []
      if (list && list.length) {
        resList = list.map(col => {
          if (col && col.columnExtend) {
            const columnExtend = JSON.parse(col.columnExtend)
            col.id = col.columnId
            col = Object.assign(col, columnExtend)
            if (col.columnSort) {
              col.sort = col.columnSort
            }
          }
          if (col && col.config) {
            const configMod = JSON.parse(col.config)
            return Object.assign(col, configMod)
          }
          return col
        })
      }
      const requiredColumnList = []
      resList.forEach(res => {
        res.inputType = this.getInputType(res.columnCode)
        if (!res.nullableFlag) {
          requiredColumnList.push(res)
        }
      })
      this.setData({requiredColumnList})
      return resList.sort((a, b) => a.sort - b.sort)
    },
    inputValue(event) {
      const columnCode = event.currentTarget.dataset.columnCode
      if (columnCode) {
        const addUpdParam = this.data.addUpdParam
        addUpdParam[columnCode] = event.detail.value
        this.setData({
          addUpdParam
        })
      }
    },
    getInputType(columnCode) {
      if (this.isIdcardColumn(columnCode)) {
        return 'idcard'
      } else if (this.isNumberColumn(columnCode) || this.isPhoneColumn(columnCode)) {
        return 'number'
      }
      return 'text'
    },
    isNumberColumn(columnCode) {
      const flag = this.data.numberColumns.find(c => c === columnCode)
      return !!flag
    },
    isIdcardColumn(columnCode) {
      const flag = this.data.idcardColumns.find(c => c === columnCode)
      return !!flag
    },
    isPhoneColumn(columnCode) {
      const flag = this.data.phoneColumns.find(c => c === columnCode)
      return !!flag
    },
    isEmailColumn(columnCode) {
      const flag = this.data.emailColumns.find(c => c === columnCode)
      return !!flag
    },
    validValue() {
      const addUpdParam = this.data.addUpdParam
      // 只校验需要显示的字段
      const typeCodeColumnList = this.data.typeCodeColumnList.filter(c => c.showForm)
      let flag = true
      if (typeCodeColumnList && typeCodeColumnList.length) {
        for (let i = 0; i < typeCodeColumnList.length; i++) {
          const k = typeCodeColumnList[i].columnCode
          const c = addUpdParam[k]
          // 校验是否必填
          const requiredColumn = this.data.requiredColumnList.find(r => r.columnCode === k)
          if (requiredColumn && !c) {
            flag = false
            wx.showToast({
              title: `【${requiredColumn.columnName}】不允许为空`,
              icon: 'none'
            })
            break
          }
          // 校验手机
          const phoneFlag = this.isPhoneColumn(k)
          if (phoneFlag && !(/^1[3-9]\d{9}$/.test(c))) {
            flag = false
            wx.showToast({
              title: `【${requiredColumn.columnName}】手机号码格式不正确，请重新填写`,
              icon: 'none',
              duration: 2000
            })
            break
          }
          // 校验邮箱
          const emailFlag = this.isEmailColumn(k)
          if (emailFlag) {
            const atIndex = c.indexOf('@')
            const dianIndex = c.lastIndexOf('.')
            if (atIndex <= 0 || dianIndex < atIndex + 2 || dianIndex > c.length - 2) {
              flag = false
              wx.showToast({
                title: `【${requiredColumn.columnName}】邮箱地址格式不正确，请重新填写`,
                icon: 'none'
              })
              break
            }
          }
        }
      }
      return flag
    },
    _save() {
      if (this.validValue()) {
        console.log('保存', this.data.addUpdParam)
        const addUpdParam = this.data.addUpdParam
        addUpdParam.type_code = this.data.typeCode
        wx.showLoading({
          title: '加载中',
        })
        const that = this
        $http.post({
          url: `cmsv2/content/save${that.data.namespace
            ? '?namespace=' + that.data.namespace : ''}`,
          data: addUpdParam,
          success(res) {
            console.log('保存成功', res)
            that.setData({
              addUpdParam: {}
            })
            wx.hideLoading()
            wx.showToast({
              title: `${that.data.saveButtonName}成功`,
              icon: 'success'
            })
          }
        })
      }
    }
  }
})
